<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '500px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      default: function (v) {
        return v
      },
    },
    chartTitle: {
      type: String,
      default: '图表',
    },
    chartType: {
      type: String,
      default: 'bar',
    }
  },
  data() {
    return {
      chart: null,
      time: [],
      data: [],
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.time = val.time.map(item => item)
        this.data = val.data.map(item => item)
        this.setOptions()
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions()
    },
    setOptions() {
      this.chart.setOption({
        title: {
          text: this.chartTitle,
          left: 10,
          top: 20,
          textStyle: {
            fontSize: 20,
          }
        },
        xAxis: {
          data: this.time,
          // type: this.chartType == 'bar' ? 'time' : null,
          boundaryGap: this.chartType == 'line' ? false : true,
          axisTick: {
            show: false
          }
        },
        grid: {
          left: '2%',
          right: this.chartType == 'line' ? '5%' : '2%',
          bottom: '10%',
          top: '20%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10]
        },
        yAxis: {
          axisTick: {
            show: false
          }
        },
        legend: {
        },
        series: [{
          itemStyle: {
            normal: {
              color: '#36a3f7',
              lineStyle: {
                color: '#36a3f7',
                width: 1
              }
            }
          },
          smooth: true,
          type: this.chartType,
          barWidth: '30%',
          data: this.data,
          animationDuration: 2800,
          animationEasing: 'cubicInOut'
        }]
      })
    }
  }
}
</script>
